package com.demo.demospringboot.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 日志工具类
 */
public class LogUtil {

  private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

  /**
   * 获取Logger实例
   */
  public static Logger getLogger(Class<?> clazz) {
    return LoggerFactory.getLogger(clazz);
  }

  /**
   * 记录方法开始执行
   */
  public static void logMethodStart(Logger logger, String methodName, String... params) {
    StringBuilder sb = new StringBuilder();
    sb.append("方法开始执行: ").append(methodName);
    if (params != null && params.length > 0) {
      sb.append(" - 参数: ");
      for (int i = 0; i < params.length; i += 2) {
        if (i + 1 < params.length) {
          sb.append(params[i]).append("=").append(params[i + 1]);
          if (i + 2 < params.length) {
            sb.append(", ");
          }
        }
      }
    }
    logger.debug(sb.toString());
  }

  /**
   * 记录方法执行完成
   */
  public static void logMethodEnd(Logger logger, String methodName, Object result) {
    logger.debug("方法执行完成: {} - 结果: {}", methodName, result);
  }

  /**
   * 记录方法执行异常
   */
  public static void logMethodException(Logger logger, String methodName, Exception e) {
    logger.error("方法执行异常: {} - 异常信息: {}", methodName, e.getMessage(), e);
  }

  /**
   * 记录业务操作
   */
  public static void logBusinessOperation(Logger logger, String operation, String... details) {
    StringBuilder sb = new StringBuilder();
    sb.append("业务操作: ").append(operation);
    if (details != null && details.length > 0) {
      sb.append(" - ");
      for (int i = 0; i < details.length; i += 2) {
        if (i + 1 < details.length) {
          sb.append(details[i]).append("=").append(details[i + 1]);
          if (i + 2 < details.length) {
            sb.append(", ");
          }
        }
      }
    }
    logger.info(sb.toString());
  }

  /**
   * 记录性能信息
   */
  public static void logPerformance(Logger logger, String operation, long startTime, long endTime) {
    long duration = endTime - startTime;
    logger.info("性能统计: {} - 耗时: {}ms", operation, duration);
  }

  /**
   * 记录当前时间
   */
  public static String getCurrentTime() {
    return LocalDateTime.now().format(formatter);
  }

  /**
   * 生成请求ID
   */
  public static String generateRequestId() {
    return "REQ_" + System.currentTimeMillis() + "_" + Thread.currentThread().getId();
  }
}